import { ApiCall } from 'tsrpc'
import { ReqSaveConfigs, ResSaveConfigs } from '../shared/api_config_editor/PtlSaveConfigs'
import { configManager } from '../config/ConfigManager'

export default async function (call: ApiCall<ReqSaveConfigs, ResSaveConfigs>) {
    try {
        const { type, configs } = call.req
        
        // 验证配置数据
        const validationErrors: string[] = []
        for (const config of configs) {
            // 这里可以添加配置验证逻辑
            if (!config.id && !config.skillId && !config.name) {
                validationErrors.push('配置必须包含唯一标识符')
            }
        }
        
        if (validationErrors.length > 0) {
            call.error('配置验证失败', {
                errors: validationErrors
            })
            return
        }
        
        // 备份现有配置
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
        const backupDir = require('path').resolve(__dirname, '../backups')
        const fs = require('fs')
        
        if (!fs.existsSync(backupDir)) {
            fs.mkdirSync(backupDir, { recursive: true })
        }
        
        // 保存配置
        const path = require('path')
        const configDir = path.resolve(__dirname, '../core/config')
        
        switch (type) {
            case 'equipment':
                // 保存装备配置
                // 这里需要根据实际的configManager API进行调整
                // 暂时保存到JSON文件
                const equipmentFile = path.join(configDir, 'equipment_templates.json')
                fs.writeFileSync(equipmentFile, JSON.stringify(configs, null, 2))
                break
                
            case 'skill':
                // 保存技能配置
                const skillFile = path.join(configDir, 'skill_configs.json')
                fs.writeFileSync(skillFile, JSON.stringify(configs, null, 2))
                break
                
            default:
                // 保存其他类型的配置
                const configFile = path.join(configDir, `${type}_configs.json`)
                fs.writeFileSync(configFile, JSON.stringify(configs, null, 2))
        }
        
        // 创建备份
        const backupFile = path.join(backupDir, `${type}_${timestamp}.json`)
        fs.writeFileSync(backupFile, JSON.stringify(configs, null, 2))
        
        // 重新加载配置管理器
        try {
            await configManager.reload()
        } catch (error) {
            console.warn('Failed to reload config manager:', error)
        }
        
        call.succ({
            data: {
                saved: configs.length,
                backupFile: backupFile
            }
        })
        
    } catch (error) {
        console.error(`Failed to save configs for type ${call.req.type}:`, error)
        call.error('保存配置失败', {
            errors: [(error as any).message]
        })
    }
}
